﻿using System;
using System.Configuration;
using System.IO;
using System.Text;
using System.Web.Configuration;
using Senparc.Weixin.MP.Agent;
using Senparc.Weixin.Context;
using Senparc.Weixin.MP.Entities;
using Senparc.Weixin.MP.MessageHandlers;
using Senparc.Weixin.MP.Helpers;
using System.Xml;
using System.Xml.Linq;
using MxWeiXinPF.Common;
using Senparc.Weixin.MP.Entities.Request;
using Senparc.Weixin.MP.AdvancedAPIs.User;
using Senparc.Weixin.MP.CommonAPIs;
using Newtonsoft.Json;
using System.Data;

namespace MxWeiXinPF.WeiXinComm.CustomMessageHandler
{
    /// <summary>
    /// 自定义MessageHandler
    /// 把MessageHandler作为基类，重写对应请求的处理方法
    /// </summary>
    public partial class CustomMessageHandler : MessageHandler<CustomMessageContext>
    {
        private string agentToken;
        private string agentUrl;
        private MxWeiXinPF.BLL.wx_dt_user_BaseData daladd;
        private MxWeiXinPF.BLL.wx_requestRule rBll;
        private MxWeiXinPF.BLL.wx_requestRuleContent rcBll;
        private WeiXCommFun wxcomm;
        private WeiXinCRMComm wxcrmcomm;
        private WeiXinSendMessageComm wxSM;

        public CustomMessageHandler(Stream inputStream, int maxRecordCount = 0)
            : base(inputStream, null, maxRecordCount, null)
        {
            this.agentUrl = "";
            this.agentToken = "";
            this.rBll = new MxWeiXinPF.BLL.wx_requestRule();
            this.rcBll = new MxWeiXinPF.BLL.wx_requestRuleContent();
            this.wxcomm = new WeiXCommFun();
            this.wxcrmcomm = new WeiXinCRMComm();
            this.wxSM = new WeiXinSendMessageComm();
            this.daladd = new MxWeiXinPF.BLL.wx_dt_user_BaseData();
            this.WeixinContext.ExpireMinutes = 10.0;
            this.WeixinContext.MaxRecordCount = 0x3e8;
        }

        public override IResponseMessageBase DefaultResponseMessage(IRequestMessageBase requestMessage)
        {
            ResponseMessageText text = base.CreateResponseMessage<ResponseMessageText>();
            text.Content = "这条消息来自DefaultResponseMessage。";
            return text;
        }

        private IResponseMessageBase EventProcess(int type, RequestMessageEventBase requestMessage, string content)
        {
            int apiid = this.wxcomm.getApiid();
            int subscribeStatusDesc = 1;
            if (type == 7)
            {
                subscribeStatusDesc = 0;
            }
            string parentopenid = null;
            int shopid = 39;
            if (!content.Equals(""))
            {
                //获取上级对象
                MxWeiXinPF.Model.users model = this.daladd.GetModel(int.Parse(content));
                parentopenid = model.wxOpenId.ToString();
                shopid = model.shopid;
            }
            string requestContent = "";
            if (requestMessage.Event.ToString().Trim() != "")
            {
                requestContent = requestMessage.Event.ToString();
            }
            if (!this.wxcomm.ExistApiidAndWxId(apiid, requestMessage.ToUserName))
            {
                wxResponseBaseMgr.Add(apiid, requestMessage.FromUserName, requestMessage.MsgType.ToString(), requestContent, "none", "未取到关键词对应的数据", requestMessage.ToUserName);
                return this.wxcomm.GetResponseMessageTxtByContent(requestMessage, "验证微帐号与微信原始帐号id不一致，可能原因【1】系统配置错误，【2】非法的数据来源", apiid);
            }
            
            UserInfoJson userDetail = this.wxcrmcomm.GetUserDetail(apiid, requestMessage.FromUserName);
            if (!this.daladd.ExistsWidAndOpenid(apiid, requestMessage.FromUserName))
            {
                
                int userid = this.daladd.addUserInfo(apiid, requestMessage.FromUserName, subscribeStatusDesc, userDetail.nickname, userDetail.sex, userDetail.language, userDetail.city, userDetail.province, userDetail.country, userDetail.headimgurl, userDetail.remark, userDetail.unionid, parentopenid, shopid);
                if (!(((type != 6) || string.IsNullOrEmpty(parentopenid)) || parentopenid.ToString().Equals("")))
                {
                    this.wxSM.SendMessageSubscribe(parentopenid, 39, requestMessage.FromUserName, string.Concat(new object[] { MyCommFun.getWebSite(), "/wxoauth.aspx?wid=", apiid, "&p=", 8, "&copenid=", requestMessage.FromUserName }));
                }
                //新关注的用户,赠送优惠券
                SendTick(userid);
            }
            else
            {
                if (type == 6)
                {
                    this.daladd.UpdateUserInfo(apiid, requestMessage.FromUserName, subscribeStatusDesc, userDetail.nickname, userDetail.sex, userDetail.language, userDetail.city, userDetail.province, userDetail.country, userDetail.headimgurl, userDetail.remark, userDetail.unionid, parentopenid, shopid);
                }
                else
                {
                    this.daladd.UpdateUserInfoUnSubscribe(apiid, requestMessage.FromUserName, subscribeStatusDesc);
                }
                if (!(((type != 6) || string.IsNullOrEmpty(parentopenid)) || parentopenid.ToString().Equals("")))
                {
                    this.wxSM.SendMessageSubscribe(parentopenid, 0x27, requestMessage.FromUserName, string.Concat(new object[] { MyCommFun.getWebSite(), "/wxoauth.aspx?wid=", apiid, "&p=", 8, "&copenid=", requestMessage.FromUserName }));
                }
            }
            int responseType = 0;
            int indexid = this.rBll.GetRuleIdAndResponseType(apiid, "reqestType=" + type, out responseType);
            if ((indexid <= 0) || (responseType <= 0))
            {
                wxResponseBaseMgr.Add(apiid, requestMessage.FromUserName, requestMessage.MsgType.ToString(), requestContent, "none", "取消关注时的提示", requestMessage.ToUserName);
                return null;
            }
            return this.wxcomm.GetResponseMessageNews(requestMessage, indexid, apiid);
            //switch (responseType)
            //{
            //    case 1:
            //        return this.wxcomm.GetResponseMessageTxt(requestMessage, indexid, apiid);

            //    case 2:
            //        return this.wxcomm.GetResponseMessageNews(requestMessage, indexid, apiid);

            //    case 3:
            //        return this.wxcomm.GetResponseMessageeMusic(requestMessage, indexid, apiid);
            //}
            //return null;
        }

        private void SendTick(int userid)
        {
            BLL.users buser = new BLL.users();
            Model.users muser = buser.GetModel(Convert.ToInt32(userid));
            Model.wx_uni_account_module moduleset = new BLL.wx_uni_account_module().GetModuleByUniacid(Common.MyCommFun.GetMainShopID());
            Model.coupon.couponsetting jsonset = JsonConvert.DeserializeObject<Model.coupon.couponsetting>(moduleset.settings);
            BLL.wx_shop_coupon_data bcoupondata = new BLL.wx_shop_coupon_data();
            if (moduleset != null && jsonset != null)
            {
                if (jsonset.enablesendnewuser == 1 && jsonset.sendnewusercouponid > 0)
                {
                    Model.wx_shop_coupon mcoupon = new BLL.wx_shop_coupon().GetModel(jsonset.sendnewusercouponid);
                    if (mcoupon != null && mcoupon.timeend > DateTime.Now)
                    {
                        DataSet ds = bcoupondata.GetList(string.Format("senduid = {0} and couponid={1} ", userid, mcoupon.id));
                        if (ds == null || ds.Tables[0].Rows.Count == 0)
                        {
                            Model.wx_shop_coupon_data thecoupon = new Model.wx_shop_coupon_data();
                            thecoupon.couponid = mcoupon.id;
                            thecoupon.shopid = Common.MyCommFun.GetMainShopID();
                            thecoupon.openid = muser.wxOpenId;
                            thecoupon.gettype = 0;
                            thecoupon.status = 0;
                            thecoupon.gettime = DateTime.Now;
                            thecoupon.usetime = DateTime.Now;
                            thecoupon.senduid = muser.id;
                            thecoupon.ordersn = 0;
                            thecoupon.sendmsgstate = 0;
                            thecoupon.sendmsgtime = DateTime.Now;

                            if (bcoupondata.Add(thecoupon) > 0)
                            {

                                //送券成功,增加日志记录
                                Model.wx_shop_coupon_log log = new Model.wx_shop_coupon_log();
                                log.shopid = Common.MyCommFun.GetMainShopID();
                                log.openid = muser.wxOpenId;
                                log.times = DateTime.Now;
                                log.couponid = mcoupon.id;
                                log.orderid = 0;
                                log.explain = "后台赠送用户";
                                log.remark = " ";
                                log.exstr1 = " ";
                                new BLL.wx_shop_coupon_log().Add(log);
                            }
                        }
                    }
                }
            }
        }
        public override IResponseMessageBase OnEvent_ClickRequest(RequestMessageEvent_Click requestMessage)
        {
            string eventKey = requestMessage.EventKey;
            int apiid = this.wxcomm.getApiid();
            string requestContent = "";
            if (requestMessage.Event.ToString().Trim() != "")
            {
                requestContent = requestMessage.Event.ToString();
            }
            else if (requestMessage.EventKey != null)
            {
                requestContent = requestContent + requestMessage.EventKey.ToString();
            }
            if (!this.wxcomm.ExistApiidAndWxId(apiid, requestMessage.ToUserName))
            {
                wxResponseBaseMgr.Add(apiid, requestMessage.FromUserName, requestMessage.MsgType.ToString(), requestContent, "none", "未取到关键词对应的数据", requestMessage.ToUserName);
                return this.wxcomm.GetResponseMessageTxtByContent(requestMessage, "验证微帐号与微信原始帐号id不一致，可能原因【1】系统配置错误，【2】非法的数据来源有问题", apiid);
            }
            int responseType = 0;
            string modelFunctionName = "";
            int modelFunctionId = 0;
            int indexid = this.rBll.GetRuleIdByKeyWords(apiid, eventKey, out responseType, out modelFunctionName, out modelFunctionId);
            if ((indexid <= 0) || (responseType <= 0))
            {
                if ((requestMessage.ToUserName == "gh_c80ca634fa2a") && (requestMessage.EventKey == "wdsluckdraw20140920"))
                {
                    return this.wxcomm.GetResponseMessageTxt(requestMessage, apiid);
                }
                wxResponseBaseMgr.Add(apiid, requestMessage.FromUserName, requestMessage.MsgType.ToString(), requestContent, "none", "未取到关键词对应的数据", requestMessage.ToUserName);
                string content = string.Concat(new object[] { MyCommFun.getWebSite(), "/shop/index.aspx?wid=", apiid, "&openid=", requestMessage.FromUserName });
                return this.wxcomm.GetResponseMessageTxtByContent(requestMessage, content, apiid);
            }
            if (modelFunctionId > 0)
            {
                return this.wxcomm.GetModuleResponse(requestMessage, modelFunctionName, modelFunctionId, apiid);
            }
            switch (responseType)
            {
                case 1:
                    return this.wxcomm.GetResponseMessageTxt(requestMessage, indexid, apiid);

                case 2:
                    return this.wxcomm.GetResponseMessageNews(requestMessage, indexid, apiid);

                case 3:
                    return this.wxcomm.GetResponseMessageeMusic(requestMessage, indexid, apiid);
            }
            return null;
        }

        public override IResponseMessageBase OnEvent_EnterRequest(RequestMessageEvent_Enter requestMessage)
        {
            ResponseMessageText text = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(requestMessage);
            text.Content = "您刚才发送了ENTER事件请求。";
            return text;
        }

        public override IResponseMessageBase OnEvent_LocationRequest(RequestMessageEvent_Location requestMessage)
        {
            ResponseMessageText text = base.CreateResponseMessage<ResponseMessageText>();
            text.Content = "这里写什么都无所谓，比如：上帝爱你！";
            return text;
        }

        public override IResponseMessageBase OnEvent_ScancodePushRequest(RequestMessageEvent_Scancode_Push requestMessage)
        {
            string eventKey = requestMessage.EventKey;
            int wid = this.wxcomm.getApiid();
            string content = "";
            string str3 = "";
            if (requestMessage.Event.ToString().Trim() != "")
            {
                str3 = requestMessage.Event.ToString();
            }
            if (!this.daladd.ExistsWidAndOpenid(wid, requestMessage.FromUserName))
            {
                if (!string.IsNullOrEmpty(requestMessage.Event.ToString()) && (requestMessage.Event.ToString().Trim() == "scan"))
                {
                    if (!requestMessage.EventKey.Contains("qrscene_"))
                    {
                        content = "/:rose欢迎光临!/:rose\n";
                    }
                    else
                    {
                        content = "二维码参数：\n" + requestMessage.EventKey.Replace("qrscene_", "");
                    }
                }
                else if (!(string.IsNullOrEmpty(requestMessage.Event.ToString()) || !(requestMessage.Event.ToString().ToLower() == "scan")))
                {
                    content = "二维码参数：\n" + requestMessage.EventKey;
                }
            }
            else
            {
                content = "二维码参数：\n" + requestMessage.EventKey;
            }
            return this.wxcomm.GetResponseMessageTxtByContent(requestMessage, content, wid);
        }

        public override IResponseMessageBase OnEvent_ScanRequest(RequestMessageEvent_Scan requestMessage)
        {
            string eventKey = requestMessage.EventKey;
            int wid = this.wxcomm.getApiid();
            string content = "";
            if (!string.IsNullOrEmpty(requestMessage.Event.ToString()) && (requestMessage.Event.ToString().Trim() == "scan"))
            {
                content = "/:rose欢迎光临!/:rose\n";
                if (!eventKey.Equals(""))
                {
                    MxWeiXinPF.Model.users model = this.daladd.GetModel(int.Parse(eventKey));
                    UserInfoJson userDetail = this.wxcrmcomm.GetUserDetail(wid, requestMessage.FromUserName);
                    if (!this.daladd.ExistsWidAndOpenid(wid, requestMessage.FromUserName))
                    {
                        this.daladd.addUserInfoForScan(wid, requestMessage.FromUserName, 1, userDetail.nickname, userDetail.sex, userDetail.language, userDetail.city, userDetail.province, userDetail.country, userDetail.headimgurl, userDetail.remark, userDetail.unionid, model.wxOpenId.ToString(), model.shopid);
                        if (!(string.IsNullOrEmpty(model.wxOpenId) || model.wxOpenId.ToString().Equals("")))
                        {
                            this.wxSM.SendMessageSubscribe(model.wxOpenId, 0x27, requestMessage.FromUserName, string.Concat(new object[] { MyCommFun.getWebSite(), "/wxoauth.aspx?wid=", wid, "&p=", 8, "&copenid=", requestMessage.FromUserName }));
                        }
                    }
                }
            }
            return this.wxcomm.GetResponseMessageTxtByContent(requestMessage, content, wid);
        }

        public override IResponseMessageBase OnEvent_SubscribeRequest(RequestMessageEvent_Subscribe requestMessage)
        {
            string content = "";
            if ((!string.IsNullOrEmpty(requestMessage.Event.ToString()) && (requestMessage.Event.ToString().Trim() == "subscribe")) && requestMessage.EventKey.Contains("qrscene_"))
            {
                content = requestMessage.EventKey.Replace("qrscene_", "");
            }
            return this.EventProcess(6, requestMessage, content);
        }

        public override IResponseMessageBase OnEvent_UnsubscribeRequest(RequestMessageEvent_Unsubscribe requestMessage)
        {
            return this.EventProcess(7, requestMessage, "");
        }

        public override void OnExecuted()
        {
            base.OnExecuted();
            this.CurrentMessageContext.StorageData = ((int)this.CurrentMessageContext.StorageData) + 1;
        }

        public override void OnExecuting()
        {
            if (this.CurrentMessageContext.StorageData == null)
            {
                this.CurrentMessageContext.StorageData = 0;
            }
            base.OnExecuting();
        }

        public override IResponseMessageBase OnImageRequest(RequestMessageImage requestMessage)
        {
            int wid = 0;
            wid = this.wxcomm.getApiid();
            WeiXCommFun fun = new WeiXCommFun();
            MxWeiXinPF.Model.wx_sq_act model = new MxWeiXinPF.BLL.wx_sq_act().GetModel(wid, DateTime.Now);
            if (model != null)
            {
                MxWeiXinPF.BLL.wx_sq_heimd _heimd = new MxWeiXinPF.BLL.wx_sq_heimd();
                if (_heimd.Exists(requestMessage.FromUserName, model.id))
                {
                    return fun.GetResponseMessageTxtByContent(requestMessage, "您在黑名单里，无法上传图片", wid);
                }
                MxWeiXinPF.BLL.wx_sq_piclist _piclist = new MxWeiXinPF.BLL.wx_sq_piclist();
                MxWeiXinPF.Model.wx_sq_piclist _piclist2 = new MxWeiXinPF.Model.wx_sq_piclist
                {
                    openid = requestMessage.FromUserName,
                    aid = new int?(model.id),
                    picUrl = requestMessage.PicUrl,
                    hasShenghe = false,
                    createDate = new DateTime?(DateTime.Now)
                };
                int num2 = _piclist.Add(_piclist2);
                if (num2 <= 0)
                {
                    return fun.GetResponseMessageTxtByContent(requestMessage, "图片上传失败，请重新上传", wid);
                }
                string content = "";
                if (model.shenghe)
                {
                    content = string.Concat(new object[] { "已经成功上传等待审核！<br/><a href=\"", MyCommFun.getWebSite(), "/weixin/shangqiang/index.aspx?wid=", wid, "&aid=", model.id, "\">查看相册</a>照片id为", num2 });
                }
                else
                {
                    content = string.Concat(new object[] { "已经成功上传点击查看<br/><a href=\"", MyCommFun.getWebSite(), "/weixin/shangqiang/index.aspx?wid=", wid, "&aid=", model.id, "\">查看相册</a>照片id为", num2 });
                }
                return fun.GetResponseMessageTxtByContent(requestMessage, content, wid);
            }
            return fun.GetResponseMessageTxtByContent(requestMessage, "您刚刚上传了一个图片", wid);
        }

        public override IResponseMessageBase OnLinkRequest(RequestMessageLink requestMessage)
        {
            ResponseMessageText text = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(requestMessage);
            text.Content = string.Format("您发送了一条连接信息：\r\nTitle：{0}\r\nDescription:{1}\r\nUrl:{2}", requestMessage.Title, requestMessage.Description, requestMessage.Url);
            return text;
        }

        public override IResponseMessageBase OnLocationRequest(RequestMessageLocation requestMessage)
        {
            LocationService service = new LocationService();
            return service.GetResponseMessage(requestMessage);
        }

        public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage)
        {
            int apiid = 0;
            try
            {
                string content = requestMessage.Content;
                apiid = this.wxcomm.getApiid();
                if (!this.wxcomm.ExistApiidAndWxId(apiid, requestMessage.ToUserName))
                {
                    wxResponseBaseMgr.Add(apiid, requestMessage.FromUserName, requestMessage.MsgType.ToString(), requestMessage.Content, "none", "验证微帐号与微信原始帐号id不一致，说明【1】配置错误，【2】数据来源有问题", requestMessage.ToUserName);
                    return this.wxcomm.GetResponseMessageTxtByContent(requestMessage, "验证微帐号与微信原始帐号id不一致，可能原因【1】系统配置错误，【2】非法的数据来源", apiid);
                }
                int responseType = 0;
                string modelFunctionName = "";
                int modelFunctionId = 0;
                int indexid = this.rBll.GetRuleIdByKeyWords(apiid, content, out responseType, out modelFunctionName, out modelFunctionId);
                if ((indexid <= 0) || (responseType <= 0))
                {
                    wxResponseBaseMgr.Add(apiid, requestMessage.FromUserName, requestMessage.MsgType.ToString(), requestMessage.Content, "none", "未取到关键词对应的数据", requestMessage.ToUserName);
                    return this.wxcomm.GetResponseMessageTxtByContent(requestMessage, "未找到匹配的关键词", apiid);
                }
                if (modelFunctionId > 0)
                {
                    return this.wxcomm.GetModuleResponse(requestMessage, modelFunctionName, modelFunctionId, apiid);
                }
                switch (responseType)
                {
                    case 1:
                        return this.wxcomm.GetResponseMessageTxt(requestMessage, indexid, apiid);

                    case 2:
                        return this.wxcomm.GetResponseMessageNews(requestMessage, indexid, apiid);

                    case 3:
                        return this.wxcomm.GetResponseMessageeMusic(requestMessage, indexid, apiid);
                }
            }
            catch (Exception exception)
            {
                new MxWeiXinPF.BLL.wx_logs().AddErrLog(apiid, "用户请求文字", "CustomMessageHandler.OnTextRequest", "错误：" + exception.Message);
            }
            return null;
        }

        public override IResponseMessageBase OnVideoRequest(RequestMessageVideo requestMessage)
        {
            ResponseMessageText text = base.CreateResponseMessage<ResponseMessageText>();
            text.Content = "您发送了一条视频信息，ID：" + requestMessage.MediaId;
            return text;
        }

        public override IResponseMessageBase OnVoiceRequest(RequestMessageVoice requestMessage)
        {
            ResponseMessageMusic music = base.CreateResponseMessage<ResponseMessageMusic>();
            music.Music.MusicUrl = "http://weixin.senparc.com/Content/music1.mp3";
            music.Music.Title = "这里是一条音乐消息";
            music.Music.Description = "来自Jeffrey Su的美妙歌声~~";
            return music;
        }

        private IResponseMessageBase ScanCodeProcess(int type, RequestMessageEventBase requestMessage)
        {
            int wid = this.wxcomm.getApiid();
            int responseType = 0;
            int indexid = this.rBll.GetRuleIdAndResponseType(wid, "reqestType=" + type, out responseType);
            switch (responseType)
            {
                case 1:
                    return this.wxcomm.GetResponseMessageTxt(requestMessage, indexid, wid);

                case 2:
                    return this.wxcomm.GetResponseMessageNews(requestMessage, indexid, wid);

                case 3:
                    return this.wxcomm.GetResponseMessageeMusic(requestMessage, indexid, wid);
            }
            return null;
        }
    }
}
